// pages/home/addInsulin/addInsulin.js
const dateTimePicker = require('../../utils/dateTimePicker.js')
const call = require('../../utils/request.js')
const app = getApp();

let chooseIndex = 1; //当前点击的第1/2的索引，对用胰岛素列表list索引
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showModalStatus:false, //是否显示胰岛素弹窗
    dateTime:null, //日期
    dateTimeArray: null,
    nowIndex: null,  //当前胰岛素的索引
    toRow: null, //滚动对应的索引，同nowIndex分开，避免点击滚动
    insulinType:{
      "intermediate":"中效",
      "premixed":"混合",
      "basal":"基础",
      "shot":"短效/速效",
    },
    //胰岛素列表
    list:[{ 
      indexs:null,
      index: null,
      value1: null,
      value2: null,
      value3: null,
      value4: null,
      id1:null,
      id2:null,
      id3:null,
      id4:null,
    },],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getInsulinList(); //获取胰岛素列表
    // this.getMealsTime()
    //this.getnowDrug(); //获取当前正在用药

    let date = new Date();
    let year = date.getFullYear();
    //日期选择器处理
    var obj = dateTimePicker.dateTimePicker(year-10, year+10);
    let lastArray = obj.dateTimeArray.pop();
    let lastTime = obj.dateTime.pop();
    this.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray,
     });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 获取当前在用药
   */
  getnowDrug(){
    wx.showLoading({
      title: '正在加载',
      mask:true
    })
    call.post('/api/system/get_medicinal').then(res=>{
      console.log("获取当前在用药",res)
      const data = res.data.data;
      const list = this.data.insulinData;
      let arr = [],obj = {},indexs=null,index = null;
      for(let i in data){
        if(i==0 || i==4){
          obj = {};
          //获取当前胰岛素id对应的索引值
          for(let y in list){
            for(let z in list[y]){
              // console.log(list[y][z].id ,data[i].medicinal_id)
              if(list[y][z].id == data[i].medicinal_id) {
                indexs=y;
                index = z;
              }
            }
          }
          obj = {indexs:indexs,index:index,[`value${data[i].meals}`]:data[i].insulin_dosage,[`id${data[i].meals}`]:data[i].id}
        }else{
          obj = Object.assign(obj,{[`value${data[i].meals}`]:data[i].insulin_dosage,[`id${data[i].meals}`]:data[i].id})
          if(i == 3 || i == 7){
            arr.push(obj);
          }
        }
      }
      for(let i = arr.length;i<1;i++){
        arr.push({ 
          indexs:null,
          index: null,
          value1: null,
          value2: null,
          value3: null,
          value4: null,
        })
      }
      
      // console.log(arr)
      this.setData({list:arr})
      wx.hideLoading();
    })
  },

  /**
   * 日期选择
   */
  changeDateTime(e) {
    this.setData({ dateTime: e.detail.value });
  },

  /**
   * 动态添加胰岛素模板
   */
  addEle(){
    let list = this.data.list;
    const index = list.length-1;
    if(list[index].name){
      wx.showToast({
        title: '请选择胰岛素1',
        icon: 'none'
      })
    }else{
      list.push({ 
        indexs:null,
        index: null,
        value1: null,
        value2: null,
        value3: null,
        value4: null,
        id1:null,
        id2:null,
        id3:null,
        id4:null,
      })
      this.setData({
        list: list
      })
    }
  },

  /**
   * 获取胰岛素列表
   */
  getInsulinList(){
    wx.showLoading({
      title: '正在加载',
      mask:true
    })
    call.post('/api/index/insulin_list').then(res=>{
      console.log("获取胰岛素列表",res)
      
      wx.hideLoading();
      //获取列表后再获取数据
      this.getnowDrug();
      const data = res.data.data
      // let list = [];
      // for(let i of data){
      //   list.push(i.medicinal_cn)
      // }
      this.setData({
        insulinData: data,
        // insulinList: list
      })
    })
  },

  /**
   * 获取餐别时间
   */
  getMealsTime(){
    call.post('/api/index/meals_time').then(res=>{
      console.log("获取血糖值列表",res.data.data)
      const data = res.data.data;
      let arr = [];
      for(let i of data.mealsconf){
        if(i.meals == 1) arr[1] = i.end_time;
        else if(i.meals == 2) arr[2] = i.end_time;
        else if(i.meals == 3) arr[3] = i.end_time;
        else if(i.meals == 4) arr[0] = arr[4] = i.end_time;
      }
      console.log(arr);
      this.setData({
        xtArr: arr
      })
    })
  },

  /**
   * 数据双向绑定
   */
  bindChange(e){
    const index = e.currentTarget.dataset.index;
    const name = e.currentTarget.dataset.name;
    this.setData({
      [`list[${index}].${name}`]: e.detail.value
    })
  },

  /**
   * 保存
   */
  save(){
    const insulinData = this.data.insulinData;
    // const dateTimeArray = this.data.dateTimeArray;
    // const dateTime = this.data.dateTime;
    // let time1 = dateTime.slice(3,5).join(':');
    // const meals = this.getMealsNum(time1);
    // let time = `${dateTimeArray[0][dateTime[0]]}-${dateTimeArray[1][dateTime[1]]}-${dateTimeArray[2][dateTime[2]]} ${dateTimeArray[3][dateTime[3]]}:${dateTimeArray[4][dateTime[4]]}`
    const list = this.data.list;
    let arr = [],arr1=[];
    for(let i of list){
      arr1 = [];
      if(i.index){ //判断是否选择胰岛素
        for(let y=1;y<5;y++){
          let value = 0;
          if(i[`value${y}`] && i[`value${y}`].trim()!=""){
            value = i[`value${y}`].trim();
          }
          let orbj = {
            medicinal_id:insulinData[i.indexs][i.index].id,
            meals:y,
            insulin_dosage: parseFloat(value)
          };
          if(i[`id${y}`]) orbj = Object.assign(orbj,{id:i[`id${y}`]})
          arr1.push(orbj)
        }
        if(arr1.length>0){
          arr.push(arr1)
        }
      }
    }
    //无填写信息保存
    if(arr.length == 0){
      wx.showToast({
        title: '请完善胰岛素信息',
        icon:'none'
      })
      return;
    }

    let data = {
      data:JSON.stringify(arr)
    }
    console.log(data)
    wx.showLoading({
      title: '正在保存',
      mask:true
    })
    call.post('/api/system/set_medicinal',data).then(res=>{
      wx.hideLoading();
      console.log("添加胰岛素",res)
      if(res.statusCode == 200 && res.data.code == 0){
        if(app.globalData.isNewPerson == 0){
          wx.switchTab({
            url: '../../pages/home/index/index',
          })
        }else{
          wx.navigateBack({
            delta: 1,
          })
        }
      }
    })
  },

  /**
   * 判断当前时间对应的餐别值meals
   */
  getMealsNum(t){
    const arr = this.data.xtArr;
    if(this.hourCompare(t,arr[0]) || this.hourCompare(arr[1],t)){ 
      return 1;
    }else if(this.hourCompare(t,arr[1])&&this.hourCompare(arr[2],t)){
      return 2;
    }else if(this.hourCompare(t,arr[2])&&this.hourCompare(arr[3],t)){
      return 3;
    }else if(this.hourCompare(t,arr[3])){
      return 4;
    }
  },

   /**
  * 时间判断大小 时:分 
  */
  hourCompare(t1,t2,t){
    let date = new Date();
    let a = t1.split(":");
    let b = t2.split(":");
    return date.setHours(a[0],a[1]) >= date.setHours(b[0],b[1]);
  },

  //显示规格弹窗
  showModal (e) {
    const index =  e.currentTarget.dataset.index;
    chooseIndex = index;
    this.setData({
      toRow:`${this.data.list[index].indexs}${this.data.list[index].index}`,
      nowIndexs: this.data.list[index].indexs,
      nowIndex: this.data.list[index].index,
    })
    
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(723).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏规格弹窗
  hideModal () {
    this.setData({
      [`list[${chooseIndex}].indexs`]: this.data.nowIndexs,
      [`list[${chooseIndex}].index`]: this.data.nowIndex
    })
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

  /**
   * 选中当前胰岛素
   */
  checkedModel(e){
    const indexs =  e.currentTarget.dataset.indexs;
    const index =  e.currentTarget.dataset.index;
    this.setData({
      nowIndexs:indexs,
      nowIndex: index
    })
  },

  /**
   * 文本框聚焦
   */
  inputFocus(e){
    const name = e.currentTarget.dataset.name;
    this.setData({
      [`${name}`]:true
    })
  },
})